package com.shengwei.truck.driver.view.ui.task;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonOrderDetailData;
import com.shengwei.truck.driver.databinding.ActivityOrderDetailBinding;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.adapter.mine.CarNumsAdapter;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.common.MyAlertDlg;
import com.shengwei.truck.driver.vm.OrderDetailViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 订单详情页
 */
public class OrderDetailActivity extends BaseActivity<OrderDetailViewModel, ActivityOrderDetailBinding> implements View.OnClickListener {
    private static final String TAG = OrderDetailActivity.class.getSimpleName() ;
    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码
    String mOrderId;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initLiveDataObersve();
        getLastIntent();
        //获取订单详情
        JsonOrderDetailData detailData = new JsonOrderDetailData();
        mDataBinding.setOrderDetail(detailData);
        mViewModel.getOrderDetail(mOrderId);
    }
    /**
     * 初始化控件显示
     */
    private void initView() {
        mDataBinding.btApplyTask.setOnClickListener(this);
        mDataBinding.contactCommonLayout.taskDetailMainLayout.setVisibility(View.VISIBLE);
        mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.imvRecvPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.tvDispatchPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.imvDispatchPhone.setOnClickListener(this);

        mDataBinding.contactCommonLayout.tvTaskNumLabel.setVisibility(View.GONE);
        mDataBinding.contactCommonLayout.lineTaskNum.setVisibility(View.GONE);
        mDataBinding.contactCommonLayout.tvTaskNum.setVisibility(View.GONE);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mDataBinding.contactCommonLayout.tvPublishTimeLabel.getLayoutParams();
        params.addRule(RelativeLayout.BELOW, R.id.lineOrerNo);
        mDataBinding.contactCommonLayout.tvPublishTimeLabel.setLayoutParams(params);
    }
    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取订单详情接口的数据
        mViewModel.getOrderDetailLiveData().observe(this, new Observer<Result<JsonOrderDetailData>>() {
            @Override
            public void onChanged(Result<JsonOrderDetailData> result) {
                result.handler(new OnCallback<JsonOrderDetailData>() {
                    @Override
                    public void onSuccess(JsonOrderDetailData data) {
                        //卸货地址可能是空，不为空再显示对应的界面
                        if(!TextUtils.isEmpty(data.unloadingCityName)){
                            mDataBinding.contactCommonLayout.loadUnloadAddress.tvUnLoadDetailAddress.setVisibility(View.VISIBLE);
                        }
                       // data.laName = MyConstant.testCustomName; //gxw+要删除恢复
                       // data.uaName = MyConstant.testCustomName; //gxw+要删除恢复
                        mDataBinding.setOrderDetail(data);
                        //如果没有出厂联系人则隐藏对应UI
                        if(TextUtils.isEmpty(data.factoryLinkPhone)){
                            mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setVisibility(View.GONE);
                            mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setVisibility(View.GONE);
                        }
                        updateGridCarNums(data);
                        updateProgress(data);
                    }
                });
            }
        });

        //监听 “申请任务接口“返回的数据
        mViewModel.getApplayTask().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        String tip = OrderDetailActivity.this.getResources().getString(R.string.applay_task_ok);
                        MyToast.showToastCenter(new WeakReference<>(OrderDetailActivity.this),tip,Toast.LENGTH_LONG,true);
                        finish();
                    }
                });
            }
        });
    }

    /**
     * @data:服务器返回的JSON数据
     * @param
     */
    private void updateProgress(JsonOrderDetailData data) {
        //更新进度条进度
        int intProgress = getProgress(data.planQuantity,data.completeQuantity);
        mDataBinding.completeProgress.setProgress(intProgress);

        //更新进度条之上的文本
        String progressText = getProgressText(data.planQuantity,data.completeQuantity,data.unit);
        mDataBinding.tvProgressText.setText(progressText);
    }


    /**
     * 根据计划总量与已完成量，来计算已完成的百分比进度
     * @param strPlanQuantity
     * @param strHasCompletedWeight
     * @return
     */
    public int getProgress(String strPlanQuantity,String strHasCompletedWeight){

        BigDecimal planQuantity = new BigDecimal(strPlanQuantity);
        BigDecimal hasCompletedWeight = new BigDecimal(strHasCompletedWeight);
        BigDecimal ret = hasCompletedWeight.divide(planQuantity,2,BigDecimal.ROUND_HALF_UP);
        BigDecimal percent = ret.multiply(new BigDecimal("100"));
        BigDecimal zero = new BigDecimal("0.00");
        int setProgress = 0;
        if(percent.compareTo(zero) <=0){
            setProgress = 1;
        }
        else{
            setProgress = percent.intValue();
        }
        return setProgress;
    }

    /**
     * 拼接进度条上面的提示文本
     * @param strPlanQuantity
     * @param strHasCompletedWeight
     * @param unit
     * @return
     */
    public String getProgressText(String strPlanQuantity,String strHasCompletedWeight,String unit){
        // 更新进度条上面的文本
        String hasComletedLabel = this.getResources().getString(R.string.has_complete_task);
        String taskTotalLabel = this.getResources().getString(R.string.task_total);
        StringBuffer progressBuffer = new StringBuffer(hasComletedLabel);
        String progressText = progressBuffer
                .append(strHasCompletedWeight)
                .append(unit).append(" / ")
                .append(taskTotalLabel)
                .append(strPlanQuantity)
                .append(unit).toString();
        return progressText;
    }

    /**
     * 更新车牌号列表
     * @param data: 服务器接口返回的数据
     */
    private void updateGridCarNums(JsonOrderDetailData data) {
        List<String> vehPlateNums = data.vehPlateNums;
        CarNumsAdapter carNumsAdapter = new CarNumsAdapter(vehPlateNums,getApplicationContext());
        mDataBinding.gridCarNums.setAdapter(carNumsAdapter);
    }

    /**
     * 获取上一页的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mOrderId = bundle.getString("id");
        }
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_order_detail;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btApplyTask:   //司机申请任务
                goApplayTask();
                break;
            case R.id.imvPublishPhone: //派单人的电话
            case R.id.tvPublishPhone:
                String publishPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.getText().toString();
                if(!TextUtils.isEmpty(publishPhone)) {
                    callPhone(publishPhone);
                }
                break;
            case R.id.imvRecvPhone: //收货人电话
            case R.id.tvReceiverPhone:
                String recvPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.getText().toString();
                if(!TextUtils.isEmpty(recvPhone)) {
                    callPhone(recvPhone);
                }
                break;
            case R.id.imvDispatchPhone:
            case R.id.tvDispatchPhone:
                String dispatchPhone = mDataBinding.contactCommonLayout.tvDispatchPhone.getText().toString();
                if(!TextUtils.isEmpty(dispatchPhone)) {
                    callPhone(dispatchPhone);
                }
                break;
        }
    }
    /**
     * 去申请任务
     */
    public void goApplayTask(){
        if(!TextUtils.isEmpty(mOrderId)) {
            MyAlertDlg.alertConfirmTip(0,R.string.is_sure_apply_task, OrderDetailActivity.this, new MyAlertDlg.AlerClickInterface() {
                @Override
                public void cancel() {
                }
                @Override
                public void sure() {
                    MyLogCat.i(TAG,"去申请任务");
                    mViewModel.applyTask(mOrderId);
                }
            });
        }
    }

    /**
     * 检查权限并拨打电话
     * @param phone
     */
    private void callPhone(final String phone) {

        //申请多个权限，当所有权限操作完后（批处理），才回调用accept函数，进而才能知道哪个权限被允许了，哪个权限被禁止了。
        final String[] permissionCall = {Manifest.permission.CALL_PHONE};
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.requestEach(permissionCall)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-permission-:" + permission.name + "---------------");
                        if (permission.name.equalsIgnoreCase(Manifest.permission.CALL_PHONE)) {
                            if (permission.granted) {//同意后调用
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + true);
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + phone); // 设置数据
                                intent.setData(data);
                                OrderDetailActivity.this.startActivity(intent); // 激活Activity组件
                            } else if (permission.shouldShowRequestPermissionRationale){//禁止，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-shouldShowRequestPermissionRationale:" + false);
                            }else {//禁止，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + false);
                                Toast.makeText(OrderDetailActivity.this, R.string.call_failed, Toast.LENGTH_SHORT).show();
                                RxjavaPermissionUtil.getInstance().alertOpenNavPermission(OrderDetailActivity.this,permissionCall);

                            }
                        }
                    }
                });
    }

}